package com.project.chat.component;

import com.alibaba.fastjson.JSON;
import com.project.chat.pojo.ChiHui;
import com.project.chat.pojo.Message;
import com.project.chat.pojo.SettingTool;
import com.project.chat.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/socket/{username}")
public class WebSocketServer {

    public static final String PUBIC_MSG = "1";
    public static final String MSG = "2";
    public static final String ROBOT_MSG = "3";

    private final Message msg = new Message();
    //专门存放管理员账号密码
    private String[] zh = new String[]{"xw", "88888888", "0"};
    //游戏服务器
    private static GameService gameService = new GameService();

    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    //存放登录的玩家用户名
    private static final Set<String> gamer = new HashSet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username){
           //如果该用户已经上线，则断开原来的连接，建立新连接
           if(sessionMap.containsKey(username))
               close(sessionMap.get(username));

           sessionMap.put(username, session);
           System.out.println("用户:"+username+"-登录");
           msg.setMsg(MSG, "--- "+username+" 加入坤粉团体-鸡王万岁！！！---");
           System.out.println(msg);
           sendAllMsg(JSON.toJSONString(msg));
    }

    @OnClose
    public void onClose( @PathParam("username") String username){
           sessionMap.remove(username);
           if(zh[0].equals(username)){
               zh[2] = "0";// 改变状态
               gameService.deleteRoom(null); //清空所有房间
               System.out.println("房间已清空");
               gamer.clear();
           }else{
               gamer.remove(username);
           }

           System.out.println("用户:"+username+"-已断开");
           msg.setMsg(MSG, "--- "+username + " 连接已断开 ---");
           System.out.println(msg);
           sendAllMsg(JSON.toJSONString(msg));
    }

    @OnMessage
    public void onMessage(String msg){
          Message message = JSON.parseObject(msg, Message.class);
          System.out.println(message);

          if(StringUtils.isEmpty(message.getTo())){
              sendAllMsg(msg);
              System.out.println("群发");
          }else {
              if("robot".equals(message.getTo())){

                  if("开始游戏".equals(message.getMsg()) ){
                      //创建房间
//                      gameService.createRoom();
                      this.msg.setMsg(PUBIC_MSG, "robot", "请输入密码： ");
                      sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));
//                      this.msg.setMsg(PUBIC_MSG, "robot", message.getFrom()+" 已加入游戏<br>请输入房间号：");
//                      System.out.println(this.msg);

                  }else if(zh[0].equals(message.getFrom()) && zh[1].equals(message.getMsg())){
                      //输入房间配置
                      this.msg.setMsg(ROBOT_MSG, "robot", message.getFrom()+" 管理员加入游戏<br>请输入房间配置(create:卡片组号, 平民数, 卧底数)：" );
                      //记录下状态
                      zh[2] = "1";
                      //发送消息
                      sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));

                  }else if(zh[0].equals(message.getFrom()) && "1".equals(zh[2])){
                      //管理员上线
                      if(message.getMsg().contains("exit")){
                          zh[2] = "0";
                          gameService.deleteRoom(null);
                      }else if(message.getMsg().contains("create:")){

                          String s = message.getMsg();
                          try{
                              s = s.substring(7);
                              //解析
                              String[] split = s.split(",");
                              SettingTool settingTool = SettingTool.createSettingTool( Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
                              //创建房间
                              int id = gameService.createRoom(settingTool);
                              ChiHui c = gameService.chiHuiTool.getChiHui(settingTool.getChiHuiId());
                              this.msg.setMsg(ROBOT_MSG, "robot", "房间id："+id + "<br> 平民："+ c.getW() + "<br>卧底："+c.getP());
                              sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));
                          }catch (Exception e){
                              this.msg.setMsg(ROBOT_MSG, "robot", "格式发生错误");
                              sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));
                          }
                      }

                  }else if("加入游戏".equals(message.getMsg())){

                      //玩家登录
                      gamer.add(message.getFrom());
                      this.msg.setMsg(ROBOT_MSG, "robot", "请输入房间号：");
                      sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));

                  }else if(gamer.contains(message.getFrom())){

                      int id;
                      try {
                          String s = message.getMsg();
                          id = Integer.parseInt(s);
                          boolean c = gameService.joinRoom(id, message.getFrom());
                          if(!c) {
                              this.msg.setMsg(ROBOT_MSG, "robot", "房间可能不存在或者已满");
                              sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));
                          }else{
                              //进入房间
                              this.msg.setMsg(ROBOT_MSG, "robot", "成功进入房间"+id);
                              sendAllMsg(JSON.toJSONString(this.msg));
                          }
                      }catch (Exception e){
                          this.msg.setMsg(ROBOT_MSG, "robot", "格式发生错误，请重新输入");
                          sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));
                      }


                  }else{
                      //robot根据获取的消息进行回复 this.msg
                      this.msg.setMsg(PUBIC_MSG, "robot", "哈哈哈， 我是机器人");
                      sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));

                      this.msg.setMsg(PUBIC_MSG, "robot", "哈哈哈， 我是机器人");
                      sendMsg(JSON.toJSONString(this.msg), sessionMap.get(message.getFrom()));
                      System.out.println(this.msg);
                  }
              }else sendMsg(msg ,sessionMap.get(message.getTo()));
          }
    }

    @OnError
    public void onError(Session session, Throwable throwable){
          zh[2] = "0";// 改变状态
          gameService.deleteRoom(null); //清空所有房间
          System.out.println("房间已清空");
          gamer.clear();
          System.out.println("发生错误");
          throwable.printStackTrace();
    }

    private String setUserNameList(){
        ArrayList<String> list = new ArrayList<>();

        for(String key : sessionMap.keySet()){
            list.add(key);
        }
        Message message = new Message();
        return JSON.toJSONString(message);
    }

    private void sendMsg(String msg, Session toSession){
        try{
            toSession.getBasicRemote().sendText(msg);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void sendAllMsg(String msg){
        try{
            for (Session toSession: sessionMap.values()){
                toSession.getBasicRemote().sendText(msg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void close(Session session)  {
        try {
            session.close();
            zh[2] = "0";// 改变状态
            gameService.deleteRoom(null); //清空所有房间
            System.out.println("房间已清空");
            gamer.clear();
        } catch (IOException e) {
            System.out.println("关闭连接发生错误。。。");
        }
    }

}
